/*
 * serialTest.c:
 ***********************************************************************
 */

#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <stdlib.h>

#include <pthread.h>

#include <wiringPi.h>
#include <wiringSerial.h>

static int fd;

void* SendHandler(void * arg){
	char *send_buf;
	send_buf = (char *)malloc(sizeof(char)*32);
	while(1){
		memset(send_buf,'\0',32);
		scanf("%s",send_buf);
		while(*send_buf){
			serialPutchar (fd,*send_buf++) ;
		}
	}
	return NULL;
}

void * RevHandler(void * argv){
	while(1){
		while (serialDataAvail (fd))
		{
			printf (" -> %d", serialGetchar (fd)) ;
			fflush (stdout) ;
		}
	}
	return 0;
}

int main ()
{
	pthread_t pid_Send;
	pthread_t pid_Rev;

	if ((fd = serialOpen ("/dev/ttyS5", 115200)) < 0)
	{
		fprintf (stderr, "Unable to open serial device: %s\n", strerror (errno)) ;
		return 1 ;
	}

	if (wiringPiSetup () == -1)
	{
		fprintf (stdout, "Unable to start wiringPi: %s\n", strerror (errno)) ;
		return 1 ;
	}

	pthread_create(&pid_Send,NULL,SendHandler,NULL);
	pthread_create(&pid_Rev,NULL,RevHandler,NULL);


	pthread_join(pid_Send,NULL);
	pthread_join(pid_Rev,NULL);



	printf ("\n") ;
	return 0 ;
}
